package com.cqc.recyclerviewdemo02;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private List<String> list = new ArrayList<>();
    private RecyclerGridAdapter adapter;
    private Toast toast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toast = Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT);
        initData();

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));//GridLayoutManager(MainActivity.this, 3)
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerGridItemDecoration(MainActivity.this));
        adapter = new RecyclerGridAdapter(list);
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new RecyclerGridAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                toast.setText(list.get(position));
                toast.show();
            }
        });
    }

    private void initData() {
        list.clear();
        for (int i = 'A'; i < 'Z'; i++) {
            list.add("" + (char) i);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add:
                list.add(1, "add");
                adapter.notifyItemInserted(1);//list中的position需要与notifyItemInserted(1)中的i一致。
                break;
            case R.id.delete:
                list.remove(3);
                adapter.notifyItemRemoved(3);
                break;
            case R.id.staggeredGrid:
                startActivity(new Intent(MainActivity.this, StaggeredGridActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
